package co.yixiang.modules.quartz.service.impl;


import co.yixiang.modules.quartz.service.PcProductParser;
import co.yixiang.modules.quartz.utils.HttpClientUtils;
import co.yixiang.modules.shop.domain.YxProductStockOut;
import co.yixiang.modules.shop.service.dto.YxProductStockOutDTO;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * 京东爬虫类
 */
@Service
public class JDPcProductParser implements PcProductParser {
    //        @Value("${pc.JD_SEARCH_STR}")
    private String JD_SEARCH_STR = "https://search.jd.com/Search?keyword={searchKey}&wq={searchKey}&enc=utf-8";
    //        @Value("${pc.SEARCH_KEY}")
    private String SEARCH_KEY = "{searchKey}";


    /**
     * @param searchKey     商品名称
     * @param count         抓取记录数
     * @param baseProductId 外部商品基础数据配置ID（可为空）
     * @return
     */
    @Override
    public List<YxProductStockOutDTO> parserList(String searchKey, int count, Integer baseProductId) {
        List<YxProductStockOutDTO> products = new ArrayList<YxProductStockOutDTO>();
        try {
            searchKey = URLEncoder.encode(searchKey, "UTF-8").replaceAll("\\+", "%20");
            String searchUrl = JD_SEARCH_STR.replace(SEARCH_KEY, searchKey);
            System.out.println("jd: " + searchUrl);

            Document doc = Jsoup.connect(searchUrl).get();
            Elements productEles = doc.getElementsByClass("gl-i-wrap");
            if (productEles != null) {
                int size = productEles.size();
                for (int i = 0; i < count; i++) {
                    if (i < size) {
                        Element productEle = productEles.get(i);
                        Element productA = productEle.getElementsByClass("p-img").get(0).getElementsByTag("a").get(0);
                        String url = "https://" + productA.attr("href").substring(2);
                        String imgUrl = "https:" + productA.getElementsByTag("img").get(0).attr("src");
                        String salePrice = productEle.getElementsByClass("p-price").get(0).getElementsByTag("i").get(0).text();
                        String title = productEle.getElementsByClass("p-name").get(0).getElementsByTag("a").get(0).attr("title");
                        YxProductStockOutDTO product = new YxProductStockOutDTO();
                        Long random=Math.round((Math.random()+1) * 1000);
                        Integer id=random.intValue()/(i+1);
                        product.setId(id);
                        product.setTitle(title);
                        product.setPrice(salePrice);
                        product.setDataSource("京东");
                        product.setImage(imgUrl);
                        product.setPname(title);
                        product.setUrl(url);
                        product.setBaseProductId(baseProductId);

                        //设置商品轮播图
                        Document detailDoc = Jsoup.connect(url).get();

                        Elements elements = detailDoc.select("#spec-list>ul>li");
                        StringBuffer result = new StringBuffer();
                        List<Map<String, Object>> sliderImageList = new ArrayList<>();
                        if (elements != null || elements.size() != 0) {
                            for (Element element : elements) {
                                //获得每个图片的url
                                Map<String, Object> map = new LinkedHashMap<>();
                                String pictureUrl = "https://img11.360buyimg.com/n1/s450x450_" + element.select("img").attr("data-url");
                                map.put("pictureUrl", pictureUrl);
                                map.put("check", false);
                                sliderImageList.add(map);

                            }
                        }
                        product.setSliderImage(sliderImageList);
                        products.add(product);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return products;
    }
    /**
     *内部商品管理库==>管理商品==>查询京东外部图片
     * @param searchKey 商品名称
     * @param count 抓取记录数
     * @param baseProductId 外部商品基础数据配置ID（可为空）
     * @return
     */
    @Override
    public List<YxProductStockOutDTO> findExternalImages(String searchKey, int count, Integer baseProductId) {
        List<YxProductStockOutDTO> products =null;
        try {
            searchKey = URLEncoder.encode(searchKey, "UTF-8").replaceAll("\\+", "%20");
            String searchUrl = JD_SEARCH_STR.replace(SEARCH_KEY, searchKey);
            System.out.println("jd: " + searchUrl);

            Document doc = Jsoup.connect(searchUrl).get();
            Elements productEles = doc.getElementsByClass("gl-i-wrap");
            if (productEles.size()>0) {
                products = new ArrayList<YxProductStockOutDTO>();
                YxProductStockOutDTO product = new YxProductStockOutDTO();
                //首图
                List<Map<String, Object>> figureImageList = new ArrayList<>();
                //轮播图
                List<Map<String, Object>> sliderImageList = new ArrayList<>();
                int size = productEles.size();
                for (int i = 0; i < count; i++) {
                    if (i < size) {
                        Element productEle = productEles.get(i);
                        Element productA = productEle.getElementsByClass("p-img").get(0).getElementsByTag("a").get(0);
                        String url = "https://" + productA.attr("href").substring(2);
                        Document detailDoc = Jsoup.connect(url).get();
                        Elements elements = detailDoc.select("#spec-list>ul>li");
                        if (elements != null || elements.size() != 0) {
                            for (Element element : elements) {
                                Long random=Math.round((Math.random()+1) * 1000);
                                Integer figureId=random.intValue()/(i+1);
                                Integer sliderId=random.intValue()/(i+1);
                                //获得每个图片的url
                                String pictureUrl = "https://img11.360buyimg.com/n1/s450x450_" + element.select("img").attr("data-url");
                                //首图
                                Map<String, Object> figureMap = new LinkedHashMap<>();
                                figureMap.put("id", figureId);
                                figureMap.put("image", pictureUrl);
                                figureImageList.add(figureMap);
                                //轮播图
                                Map<String, Object> sliderMap = new LinkedHashMap<>();
                                sliderMap.put("id", sliderId);
                                sliderMap.put("pictureUrl", pictureUrl);
                                sliderMap.put("check", false);
                                sliderImageList.add(sliderMap);

                            }
                        }
                    }
                }
                product.setSliderImage(sliderImageList);
                product.setFigureImage(figureImageList);
                products.add(product);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return products;
    }

}
